<script setup lang="ts">
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 模块导入 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

import { computed, nextTick, reactive, ref, shallowRef, watch } from 'vue';
import type { TreeOption } from 'naive-ui';
import dayjs from 'dayjs';
import { useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { useAuth } from '@/hooks/business/auth';
import { fetchAddDmCompany, fetchGetDmCompany, fetchGetMyUniqueProvinceCityCounty, fetchGetOrgUnitTree, fetchUpdateDmCompany } from '@/service/api';
// import { useDict } from '@/hooks/business/dict';
import { TreeUtil } from '@/utils/z';

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组件名称 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

defineOptions({
  name: 'DmCompanyOperateModal'
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组合式函数 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const { validate, restoreValidation } = useNaiveForm();

const { currentOrgPosition, userInfo } = useAuth();

// const { dictOptions } = useDict();

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 父子传参 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

interface Props {
  operateType: OperateType;
  rowData?: Api.Dimo.Company | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

export type OperateType = NaiveUI.TableOperateType | 'view';

const isAdd = computed(() => props.operateType === 'add');

const isEdit = computed(() => props.operateType === 'edit');

const isView = computed(() => props.operateType === 'view');

const addKey = computed(() => `DMCOMPANY${userInfo()?.userName}ADD`);

const editKey = computed(() => `DMCOMPANY${userInfo()?.userName}EDIT${props.rowData?.id}`);

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('common.add'),
    edit: $t('common.edit'),
    view: '查看'
  };
  return `【${titles[props.operateType]}】废旧农用薄膜回收利用企业调查表`;
});

type Model = Api.Dimo.Company;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: '',
    createUser: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    tenantId: '',
    orgId: '',
    positionId: '',
    reportUnit: '',
    reportDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    reportPerson: '',
    reportPersonContactInfo: '',
    investPerson: '',
    investPersonContactInfo: '',
    countyAuthStatus: false,
    countyAuthDate: '',
    countyAuthUserId: '',
    cityAuthStatus: false,
    cityAuthDate: '',
    cityAuthUserId: '',
    provinceAuthStatus: false,
    provinceAuthDate: '',
    provinceAuthUserId: '',
    comment: '',
    provinceCityCountyInfo: {
      provinceId: '',
      provinceName: '',
      cityId: '',
      cityName: '',
      countyId: '',
      countyName: ''
    },
    companyCounties: [createCompanyCounty()]
  };
}

function createCompanyCounty(): Api.Dimo.DmCompanyCounty {
  return {
    countyId: '',
    companyDetails: [createCompanyDetail()]
  };
}

function createCompanyDetail(): Api.Dimo.DmCompanyDetail {
  return {
    id: '',
    createUser: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    tenantId: '',
    companyId: '',
    countyId: '',
    name: '',
    address: '',
    contactInfo: '',
    yearDealCapacity: 0,
    recycle: 0,
    recycleByCompany: 0,
    recycleByBin: 0,
    recycleDm: 0,
    recyclePm: 0,
    reuse: 0,
    reuseDm: 0,
    reuseDmRaw: 0,
    reuseDmFuel: 0,
    reuseDmOther: 0,
    reusePm: 0,
    recyclePriceDm: 0,
    recyclePricePm: 0,
    runningStatus: false,
    subsidy: 0,
    comment: ''
  };
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const orgType = ref<string>(currentOrgPosition()?.orgType || '');

const orgTreeOptions = shallowRef<TreeOption[]>([]);

const showTable = ref<boolean>(true);

const isCountyOperate = computed(
  () => (isAdd.value && orgType.value === 'County') || TreeUtil.findNodeInTree(orgTreeOptions.value, model.provinceCityCountyInfo.countyId)
);

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

function handleInitModel() {
  // 首先初始化一个空结构，利于监听事件
  Object.assign(model, createDefaultModel());

  // 初始化我的组织树
  fetchGetOrgUnitTree().then(({ error, data }) => {
    if (!error && data) {
      orgTreeOptions.value = data.map(toTreeOptionNode);
    }
  });

  let localData = null;
  if (props.operateType === 'add') {
    localData = localStorage.getItem(addKey.value);
  } else if (props.operateType === 'edit') {
    localData = localStorage.getItem(editKey.value);
  }

  if (localData) {
    window.$dialog?.info({
      title: $t('common.tip'),
      content: '检测到上次您有未保存的数据，是否继续使用该数据进行操作?',
      positiveText: $t('common.confirm'),
      negativeText: $t('common.cancel'),
      onPositiveClick: () => {
        showTable.value = false;
        nextTick(() => {
          Object.assign(model, JSON.parse(localData));
          showTable.value = true;
        });
      },
      onNegativeClick: () => {
        if (isAdd.value) {
          localStorage.removeItem(addKey.value);
        } else if (isEdit.value) {
          localStorage.removeItem(editKey.value);
        }
        handleAEV();
      }
    });
  } else {
    handleAEV();
  }
}

function handleAEV() {
  if (props.operateType === 'add') {
    model.reportPerson = userInfo()?.realName || '';
    fetchGetMyUniqueProvinceCityCounty().then(({ error, data }) => {
      if (!error && data) {
        model.provinceCityCountyInfo = data;
        model.orgId = data.countyId ?? data.cityId ?? data.provinceId;
      }
    });
  } else if (['edit', 'view'].includes(props.operateType) && props.rowData) {
    showTable.value = false;
    fetchGetDmCompany(props.rowData?.id || '').then(({ error, data }) => {
      if (!error && data) {
        data.reportDate = dayjs(data.reportDate).format('YYYY-MM-DD HH:mm:ss');
        Object.assign(model, data);
        showTable.value = true;
      }
    });
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  const func = isAdd.value ? fetchAddDmCompany : fetchUpdateDmCompany;
  if (isAdd.value) {
    model.orgId = currentOrgPosition()?.orgId || '';
    model.positionId = currentOrgPosition()?.positionId || '';
  }
  const { error, data } = await func(model);
  if (!error && data) {
    window.$message?.success(isAdd.value ? $t('common.addSuccess') : $t('common.updateSuccess'));
    if (isAdd.value) {
      localStorage.removeItem(addKey.value);
    } else if (isEdit.value) {
      localStorage.removeItem(editKey.value);
    }
    closeModal();
    emit('submitted');
  }
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

function toTreeOptionNode(item: Api.SystemManage.OrgUnitTree): TreeOption {
  const option: TreeOption = {
    key: item.id,
    label: item.name,
    disabled: item.orgType !== 'County'
  };
  if (item.children && item.children.length > 0) {
    option.children = item.children.map(toTreeOptionNode);
  }
  return option;
}

/** 新增县 */
function plusCounty(index: number, type: string) {
  if (type === 'push') {
    model.companyCounties.push(createCompanyCounty());
  } else {
    model.companyCounties.splice(index + 1, 0, createCompanyCounty());
  }
}

/** 删除县 */
function reduceCounty(index: number) {
  model.companyCounties.splice(index, 1);
}

/** 上移县 */
function upCounty(index: number) {
  showTable.value = false;
  nextTick(() => {
    const element = model.companyCounties.splice(index, 1)[0];
    model.companyCounties.splice(index - 1, 0, element);
    showTable.value = true;
  });
}

/** 下移县 */
function downCounty(index: number) {
  showTable.value = false;
  nextTick(() => {
    const element = model.companyCounties.splice(index, 1)[0];
    model.companyCounties.splice(index + 1, 0, element);
    showTable.value = true;
  });
}

/** 新增企业 */
function plusCompany(rows: Api.Dimo.DmCompanyDetail[], index: number, type: string) {
  if (type === 'push') {
    rows.push(createCompanyDetail());
  } else {
    rows.splice(index + 1, 0, createCompanyDetail());
  }
}

/** 删除企业 */
function reduceCompany(rows: Api.Dimo.DmCompanyDetail[], index: number) {
  rows.splice(index, 1);
}

/** 表格滚动事件 */
const originalTableRef = ref();
const floatingTableRef = ref();
const lastScrollHeight = ref<number>(0);
function handleTableScroll() {
  const tableContainer = originalTableRef.value.parentNode;
  const scrollTop = tableContainer.scrollTop;
  if (lastScrollHeight.value === 0 && scrollTop > 1) {
    lastScrollHeight.value = scrollTop;
    const theadClone = originalTableRef.value.querySelector('thead').cloneNode(true);
    floatingTableRef.value.appendChild(theadClone);
    const originalHeaders = originalTableRef.value.querySelectorAll('th');
    const floatingHeaders = floatingTableRef.value.querySelectorAll('th');
    originalHeaders.forEach((header: any, index: any) => {
      floatingHeaders[index].style.width = `${header.offsetWidth}px`;
    });
    floatingTableRef.value.style.top = `${scrollTop}px`;
    floatingTableRef.value.style.display = 'table';
  } else if (lastScrollHeight.value !== 0 && scrollTop === 0) {
    lastScrollHeight.value = scrollTop;
    floatingTableRef.value.style.top = `${scrollTop}px`;
    floatingTableRef.value.innerHTML = '';
    floatingTableRef.value.style.display = 'none';
  } else if (lastScrollHeight.value !== 0 && scrollTop !== 0) {
    lastScrollHeight.value = scrollTop;
    floatingTableRef.value.style.top = `${scrollTop}px`;
  }
}

function tempSave() {
  if (isAdd.value) {
    localStorage.removeItem(addKey.value);
    const plainObject = JSON.parse(JSON.stringify(model));
    localStorage.setItem(addKey.value, JSON.stringify(plainObject));
  } else if (isEdit.value) {
    const plainObject = JSON.parse(JSON.stringify(model));
    localStorage.setItem(editKey.value, JSON.stringify(plainObject));
  }
  window.$message?.success('临时保存成功');
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// ---------- 页面统计 ----------

// 县合计
const countyCount = ref<Map<string, Api.Dimo.DmCompanyDetail>>(new Map());
// 市合计
const cityCount = ref<Api.Dimo.DmCompanyDetail>(createCompanyDetail());
watch(
  () => model.companyCounties,
  () => {
    const countyCount1: Map<string, Api.Dimo.DmCompanyDetail> = new Map();
    const cityCount1: Api.Dimo.DmCompanyDetail = createCompanyDetail();
    model.companyCounties.forEach(county => {
      if (!countyCount1.has(county.countyId)) {
        countyCount1.set(county.countyId, createCompanyDetail());
      }
      const county1 = countyCount1.get(county.countyId)!;
      county.companyDetails.forEach(detail => {
        county1.yearDealCapacity += detail.yearDealCapacity;
        county1.recycle += detail.recycle;
        county1.recycleByCompany += detail.recycleByCompany;
        county1.recycleByBin += detail.recycleByBin;
        county1.recycleDm += detail.recycleDm;
        county1.recyclePm += detail.recyclePm;
        county1.reuse += detail.reuse;
        county1.reuseDm += detail.reuseDm;
        county1.reuseDmRaw += detail.reuseDmRaw;
        county1.reuseDmFuel += detail.reuseDmFuel;
        county1.reuseDmOther += detail.reuseDmOther;
        county1.reusePm += detail.reusePm;
        county1.recyclePriceDm += detail.recyclePriceDm;
        county1.recyclePricePm += detail.recyclePricePm;
        county1.subsidy += detail.subsidy;

        cityCount1.yearDealCapacity += detail.yearDealCapacity;
        cityCount1.recycle += detail.recycle;
        cityCount1.recycleByCompany += detail.recycleByCompany;
        cityCount1.recycleByBin += detail.recycleByBin;
        cityCount1.recycleDm += detail.recycleDm;
        cityCount1.recyclePm += detail.recyclePm;
        cityCount1.reuse += detail.reuse;
        cityCount1.reuseDm += detail.reuseDm;
        cityCount1.reuseDmRaw += detail.reuseDmRaw;
        cityCount1.reuseDmFuel += detail.reuseDmFuel;
        cityCount1.reuseDmOther += detail.reuseDmOther;
        cityCount1.reusePm += detail.reusePm;
        cityCount1.recyclePriceDm += detail.recyclePriceDm;
        cityCount1.recyclePricePm += detail.recyclePricePm;
        cityCount1.subsidy += detail.subsidy;
      });
    });
    countyCount.value = countyCount1;
    cityCount.value = cityCount1;
  },
  { deep: true }
);
</script>

<template>
  <NModal
    v-model:show="visible"
    class="modal-container"
    :style="{ width: 'calc(100vw - 20px)' }"
    :title="title"
    preset="card"
    :close-on-esc="false"
    :mask-closable="false"
  >
    <div class="mb-12px">
      <NGrid v-if="!isView" x-gap="12" :cols="isCountyOperate ? 4 : 3">
        <NGi>
          <NInput v-model:value="model.reportUnit" type="text">
            <template #prefix>填报单位：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.provinceCityCountyInfo.cityName" type="text" disabled>
            <template #prefix>市：</template>
          </NInput>
        </NGi>
        <NGi v-if="isCountyOperate">
          <NInput v-model:value="model.provinceCityCountyInfo.countyName" type="text" disabled>
            <template #prefix>县：</template>
          </NInput>
        </NGi>
        <NGi>
          <NDatePicker v-model:formatted-value="model.reportDate" type="date" value-format="yyyy-MM-dd HH:mm:ss" :disabled="isView" />
        </NGi>
      </NGrid>
      <NSpace v-else>
        <span class="mr-60px">
          <b>填报单位：</b>
          {{ model.reportUnit }}
        </span>
        <span class="mr-60px">
          <b>市：</b>
          {{ model.provinceCityCountyInfo.cityName }}
        </span>
        <span v-if="isCountyOperate" class="mr-60px">
          <b>县：</b>
          {{ model.provinceCityCountyInfo.countyName }}
        </span>
        <span>
          <b>填报日期：</b>
          {{ dayjs(model.reportDate).format('YYYY-MM-DD') }}
        </span>
      </NSpace>
    </div>
    <div class="table-container relative mb-12px overflow-y-scroll" :class="{ 'view-h': isView }" @scroll="handleTableScroll">
      <table ref="floatingTableRef" class="absolute left-0 z-999"></table>
      <table ref="originalTableRef">
        <thead>
          <tr>
            <th rowspan="3" class="w-200px">县(市、区)</th>
            <th rowspan="3">
              年处理能
              <br />
              力(千克)
            </th>
            <th colspan="5">废旧农用薄膜回收量(千克)</th>
            <th colspan="6">废旧农用薄膜再利用量(千克)</th>
            <th rowspan="3">
              地膜废旧
              <br />
              回收价格
              <br />
              (元/千克)
            </th>
            <th rowspan="3">
              棚膜废旧
              <br />
              回收价格
              <br />
              (元/千克)
            </th>
            <th rowspan="3">
              是否正常
              <br />
              运行
            </th>
            <th rowspan="3">
              <div>补贴标准</div>
              <div>(元/千克)</div>
            </th>
          </tr>
          <tr>
            <th rowspan="2">回收量</th>
            <th colspan="2">其中，按回收来源分</th>
            <th colspan="2">其中，按农膜种类分</th>
            <th rowspan="2">再利用量</th>
            <th colspan="4">其中，废旧地膜再利用量</th>
            <th rowspan="2">
              其中废旧
              <br />
              棚膜再利
              <br />
              用量
            </th>
          </tr>
          <tr>
            <th>
              企业直接
              <br />
              回收量
            </th>
            <th>
              回收站点
              <br />
              交售量
            </th>
            <th>
              地膜回收
              <br />
              量
            </th>
            <th>
              棚膜回收
              <br />
              量
            </th>
            <th>再利用量</th>
            <th>
              其中原料
              <br />
              化利用量
            </th>
            <th>
              其中燃料
              <br />
              化利用量
            </th>
            <th>
              其中其他
              <br />
              方式再利
              <br />
              用量
            </th>
          </tr>
        </thead>
        <tbody v-if="showTable">
          <template v-for="(county, county_index) in model.companyCounties" :key="`city_${county_index}`">
            <template v-for="(detail, detail_index) in county.companyDetails" :key="`detail_${detail_index}`">
              <tr class="bg-[#f5f5f5]">
                <td v-if="detail_index === 0" :rowspan="county.companyDetails.length * 2" valign="top" class="pb-9px pt-9px">
                  <NTreeSelect
                    v-if="!isView"
                    :options="orgTreeOptions"
                    :default-value="county.countyId"
                    size="small"
                    @update:value="
                      value => {
                        county.countyId = value;
                      }
                    "
                  />
                  <span v-else>{{ TreeUtil.findNodeInTree(orgTreeOptions, county.countyId)?.label }}</span>
                  <div v-if="['City'].includes(orgType) && !isView">
                    <NButton
                      ghost
                      circle
                      type="primary"
                      size="tiny"
                      class="ml-1px mt-3px"
                      @click="plusCounty(county_index, county_index === model.companyCounties.length - 1 ? 'push' : 'insert')"
                    >
                      <template #icon>
                        <icon-carbon:add />
                      </template>
                    </NButton>
                    <NButton ghost circle type="primary" size="tiny" class="ml-5px mt-3px" @click="reduceCounty(county_index)">
                      <template #icon>
                        <icon-carbon:close />
                      </template>
                    </NButton>
                    <NButton v-if="county_index !== 0" ghost circle type="error" size="tiny" class="ml-5px mt-3px" @click="upCounty(county_index)">
                      <template #icon>
                        <icon-carbon:arrow-up />
                      </template>
                    </NButton>
                    <NButton
                      v-if="county_index !== model.companyCounties.length - 1"
                      ghost
                      circle
                      type="error"
                      size="tiny"
                      class="ml-5px mt-3px"
                      @click="downCounty(county_index)"
                    >
                      <template #icon>
                        <icon-carbon:arrow-down />
                      </template>
                    </NButton>
                  </div>
                </td>
                <td colspan="16" :class="{ btw0: !isView, 'pt-9px': !isView }">
                  <NGrid v-if="!isView" x-gap="1" :cols="4">
                    <NGi>
                      <NInput v-model:value="detail.name" type="text" size="small">
                        <template #prefix>企业名称：</template>
                      </NInput>
                    </NGi>
                    <NGi>
                      <NInput v-model:value="detail.address" type="text" size="small">
                        <template #prefix>企业地址：</template>
                      </NInput>
                    </NGi>
                    <NGi>
                      <NInput v-model:value="detail.contactInfo" type="text" size="small">
                        <template #prefix>联系方式：</template>
                      </NInput>
                    </NGi>
                    <NGi>
                      <NButton
                        ghost
                        circle
                        type="primary"
                        size="tiny"
                        class="ml-3px mt-3px"
                        @click="
                          plusCompany(county.companyDetails, detail_index, county_index === county.companyDetails.length - 1 ? 'push' : 'insert')
                        "
                      >
                        <template #icon>
                          <icon-carbon:add />
                        </template>
                      </NButton>
                      <NButton
                        v-if="county.companyDetails.length > 1"
                        ghost
                        circle
                        type="error"
                        size="tiny"
                        class="ml-5px mt-3px"
                        @click="reduceCompany(county.companyDetails, detail_index)"
                      >
                        <template #icon>
                          <icon-carbon:close />
                        </template>
                      </NButton>
                    </NGi>
                  </NGrid>
                  <NSpace v-else>
                    <span class="ml-5px mr-60px">
                      <b>企业名称：</b>
                      {{ detail.name }}
                    </span>
                    <span class="mr-60px">
                      <b>企业地址：</b>
                      {{ detail.address }}
                    </span>
                    <span>
                      <b>联系方式：</b>
                      {{ detail.contactInfo }}
                    </span>
                  </NSpace>
                </td>
              </tr>
              <tr class="bg-[#f5f5f5]">
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.yearDealCapacity" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.yearDealCapacity }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.recycle" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.recycle }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.recycleByCompany" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.recycleByCompany }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.recycleByBin" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.recycleByBin }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.recycleDm" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.recycleDm }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.recyclePm" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.recyclePm }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.reuse" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.reuse }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.reuseDm" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.reuseDm }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.reuseDmRaw" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.reuseDmRaw }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.reuseDmFuel" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.reuseDmFuel }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.reuseDmOther" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.reuseDmOther }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.reusePm" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.reusePm }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.recyclePriceDm" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.recyclePriceDm }}</div>
                </td>
                <td class="w-102px" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.recyclePricePm" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.recyclePricePm }}</div>
                </td>
                <td class="w-102px text-center" :class="{ btw0: !isView, 'pb-9px': !isView }">
                  <NRadioGroup v-if="!isView" v-model:value="detail.runningStatus">
                    <NRadio :value="true" label="是" />
                    <NRadio :value="false" label="否" />
                  </NRadioGroup>
                  <div v-else>{{ detail.runningStatus ? '是' : '否' }}</div>
                </td>
                <td class="w-102px" :class="{ 'pb-9px': !isView }">
                  <NInputNumber v-if="!isView" v-model:value="detail.subsidy" clearable :precision="2" :show-button="false" size="small" />
                  <div v-else class="text-right">{{ detail.subsidy }}</div>
                </td>
              </tr>
            </template>
            <tr class="bg-[#fedb61]">
              <td>{{ TreeUtil.findNodeInTree(orgTreeOptions, county.countyId)?.label }} 合计</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.yearDealCapacity }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.recycle }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.recycleByCompany }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.recycleByBin }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.recycleDm }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.recyclePm }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.reuse }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.reuseDm }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.reuseDmRaw }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.reuseDmFuel }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.reuseDmOther }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.reusePm }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.recyclePriceDm }}</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.recyclePricePm }}</td>
              <td class="text-center">-</td>
              <td class="text-right">{{ countyCount.get(county.countyId)?.subsidy }}</td>
            </tr>
          </template>
          <tr v-if="!isCountyOperate">
            <td class="">{{ TreeUtil.findNodeInTree(orgTreeOptions, model.provinceCityCountyInfo.cityId)?.label }} 合计</td>
            <td class="text-right">{{ cityCount.yearDealCapacity }}</td>
            <td class="text-right">{{ cityCount.recycle }}</td>
            <td class="text-right">{{ cityCount.recycleByCompany }}</td>
            <td class="text-right">{{ cityCount.recycleByBin }}</td>
            <td class="text-right">{{ cityCount.recycleDm }}</td>
            <td class="text-right">{{ cityCount.recyclePm }}</td>
            <td class="text-right">{{ cityCount.reuse }}</td>
            <td class="text-right">{{ cityCount.reuseDm }}</td>
            <td class="text-right">{{ cityCount.reuseDmRaw }}</td>
            <td class="text-right">{{ cityCount.reuseDmFuel }}</td>
            <td class="text-right">{{ cityCount.reuseDmOther }}</td>
            <td class="text-right">{{ cityCount.reusePm }}</td>
            <td class="text-right">{{ cityCount.recyclePriceDm }}</td>
            <td class="text-right">{{ cityCount.recyclePricePm }}</td>
            <td class="text-center">-</td>
            <td class="text-right">{{ cityCount.subsidy }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="mb-12px">
      <NGrid v-if="!isView" x-gap="12" :cols="4">
        <NGi>
          <NInput v-model:value="model.reportPerson" :disabled="isView">
            <template #prefix>填报人：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.reportPersonContactInfo" :disabled="isView">
            <template #prefix>联系方式：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.investPerson" :disabled="isView">
            <template #prefix>调查员：</template>
          </NInput>
        </NGi>
        <NGi>
          <NInput v-model:value="model.investPersonContactInfo" :disabled="isView">
            <template #prefix>联系方式：</template>
          </NInput>
        </NGi>
      </NGrid>
      <NSpace v-else>
        <span class="mr-60px">
          <b>填报人：</b>
          {{ model.reportPerson }}
        </span>
        <span class="mr-60px">
          <b>联系方式：</b>
          {{ model.reportPersonContactInfo }}
        </span>
        <span class="mr-60px">
          <b>调查员：</b>
          {{ model.investPerson }}
        </span>
        <span>
          <b>联系方式：</b>
          {{ model.investPersonContactInfo }}
        </span>
      </NSpace>
      <div class="h-12px"></div>
      <NInput v-if="!isView" v-model:value="model.comment" placeholder="备注" :disabled="isView" />
      <span v-else>
        <b>备注：</b>
        {{ model.comment }}
      </span>
    </div>
    <template #footer>
      <NSpace v-if="!isView" justify="end">
        <NButton type="warning" @click="tempSave">临时保存</NButton>
        <NButton type="error" @click="closeModal">
          {{ $t('common.cancel') }}
        </NButton>
        <NButton type="primary" @click="handleSubmit">
          {{ $t('common.save') }}
        </NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped>
.table-container {
  border: 1px solid #e5e7eb;
  margin-bottom: 12px;
  height: calc(100vh - 282px);

  &.view-h {
    height: calc(100vh - 212px);
  }

  table {
    width: 100%;
    border-collapse: collapse;

    th,
    td {
      border: 1px solid #e5e7eb;
    }

    thead {
      background-color: #fff;

      tr {
        &:first-child {
          th {
            border-top-width: 0px;
          }
        }
      }
    }

    thead,
    tbody {
      tr {
        th,
        td {
          padding: 5px;

          &:first-child {
            border-left-width: 0px;
          }
        }
      }
    }
  }
}
</style>
